package cn.swu.cs.lessonsix

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentManager

class MainActivity : AppCompatActivity() {

    lateinit var manager: FragmentManager


    companion object {
        val TAG_LIFE = "life"
        val TAG_WORK = "work"
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
    }

    private fun initView() {
        manager = supportFragmentManager
    }


    fun showLife() {
        showFragment(TAG_LIFE)
    }

    fun showWork() {
        showFragment(TAG_WORK)
    }

    private fun showFragment(tag: String) {

        val hint = findViewById<TextView>(R.id.hint)
        hint.isVisible = false

        val frag = manager.findFragmentByTag(tag) ?:
            if (tag == TAG_LIFE) RightFragment("我的生活") else RightFragment("我的工作")

        val trans = manager.beginTransaction()

        manager.fragments.forEach {
            if(it != frag && it !is LeftFragment){
                trans.hide(it)
            }
        }

        if(frag.isAdded){
            trans.show(frag)
        }else{
            trans.add(R.id.right, frag,tag)
        }

        trans.commit()

    }
}